<template>
  <div class="app-container">
    <el-form>
      <el-form-item label="启动优惠劵" label-width="88px">
        <el-switch
          v-model="couponEnabledFlag"
          :disabled="couponEnabledFlag === '1'"
          active-value="1"
          inactive-value="0"
          @change="handleFlagChange()"
        ></el-switch>
      </el-form-item>
      <hr />
    </el-form>
    <div v-if="couponEnabledFlag == 1">
      <el-form
        :model="queryForm"
        size="small"
        ref="queryForm"
        :inline="true"
        label-width="88px"
      >
        <el-form-item label="油企名称:" prop="enterpriseId" v-if="authUser">
          <el-select
            v-model="queryForm.enterpriseId"
            :clearable="true"
            filterable
            placeholder="请选择油企"
            @change="handleSelectChange"
          >
            <el-option
              v-for="(item, index) in enterpriseList"
              :key="index"
              :value="item.enterpriseId"
              :label="item.enterpriseName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="油站名称:" prop="stationId" clearable>
          <el-select
            v-model="queryForm.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
          >
            <el-option
              v-for="item in stationList"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="优惠券ID:" prop="id">
          <el-input
            placeholder="请输入优惠券ID"
            clearable
            v-model="queryForm.id"
          />
        </el-form-item>

        <el-form-item label="优惠券名称:" prop="couponRemark" v-if="!authUser">
          <el-input
            v-model="queryForm.couponRemark"
            placeholder="请输入优惠卷名称"
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleQuery"
            >搜索</el-button
          >
          <el-button
            type="info"
            icon="el-icon-refresh"
            size="mini"
            @click="resetQuery"
            >重置</el-button
          >
          <el-button
            type="text"
            style="margin-left: 10px"
            id="closeSearchBtn"
            @click="
              (closeSearch) => {
                collapse = !collapse;
              }
            "
          >
            {{ collapse ? "收起" : "展开" }}
            <i
              :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"
            ></i>
          </el-button>
        </el-form-item>
        <div v-show="collapse">
          <el-form-item label="优惠券名称:" prop="couponRemark" v-if="authUser">
            <el-input
              v-model="queryForm.couponRemark"
              placeholder="请输入优惠卷名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="优惠券类型:" prop="couponType">
            <el-select
              v-model="queryForm.couponType"
              clearable
              placeholder="请选择"
            >
              <el-option label="现金券" value="1"></el-option>
              <el-option label="折扣券" value="2"></el-option>
              <!-- <el-option label="兑换券" value="3"></el-option> -->
              <el-option label="洗车券" value="4"></el-option>
              <el-option label="立减券" value="5"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="生效状态:" prop="status">
            <el-select
              v-model="queryForm.status"
              clearable
              placeholder="请选择"
            >
              <el-option label="待生效" value="0"></el-option>
              <el-option label="生效中" value="1"></el-option>
              <el-option label="生效已暂停" value="2"></el-option>
              <el-option label="已失效" value="3"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="创建时间:" prop="getCreateTime">
            <el-date-picker
              style="width: 370px"
              v-model="dateRangeCreatedDate"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-bottom: 14px">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
        <el-button
          type="danger"
          :disabled="selectionChangeList.length < 1"
          icon="el-icon-delete"
          size="mini"
          @click="handleDelete"
          >删除</el-button
        >
          <el-button type="primary" plain size="mini" @click="showSelfHexiao">
            优惠券自助核销
          </el-button>

        <!-- <el-button disable size="mini">导出兑换码</el-button> -->
      </div>
      <el-table
        :data="couponList"
        @selection-change="selectionChange"
      >
        <el-table-column type="selection" width="55" />
        <!-- <af-table-column label="优惠券标识" align="left" prop="couponRemark" fixed="left" /> -->
        <af-table-column label="油站名称" prop="stationName" />
        <af-table-column label="优惠券名称" align="left" prop="couponRemark" />
        <af-table-column label="优惠券ID" prop="id" />
        <af-table-column
          label="优惠券类型"
          prop="couponType"
          :formatter="formatterCouponType"
        />
        <af-table-column
          label="生效状态"
          prop="status"
          :formatter="formatterStatus"
          width="120"
        />
        <af-table-column label="发放有效期" align="left">
          <template slot-scope="scope">
            <span>{{ scope.row.startDate }} - {{ scope.row.endDate }}</span>
          </template>
        </af-table-column>
        <af-table-column label="创建时间" prop="createTime" />
        <el-table-column
          label="优惠说明"
          prop="couponDetails"
          min-width="150"
          show-overflow-tooltip
        />
        <!-- <af-table-column label="卡片类型" align="left">
          <template slot-scope="scope">
            {{
              scope.row.couponType == 1
              ? "现金劵" + "--面值：" + scope.row.couponAmt + "元"
              : ""
            }}
            {{
              scope.row.couponType == 2
              ? "折扣券" + "--折扣：" + scope.row.couponAmt + "% "
              : ""
            }}
            {{
              scope.row.couponType == 3
              ? "兑换券" + "--商品：" + scope.row.couponName
              : ""
            }}
          </template>
        </af-table-column> -->
        <!-- <af-table-column label="使用状态" align="left">
          <template slot-scope="scope">
            {{
              "共生成了" +
              scope.row.couponNum +
              "张，已领取" +
              scope.row.getCouponNum +
              "张，已使用" +
              scope.row.useCouponNum +
              "张"
            }}
          </template>
        </af-table-column> -->
        <af-table-column label="优惠券有效期" align="left">
          <template slot-scope="scope">
            {{
              (scope.row.effectiveTimeType == 1
                ? scope.row.effectiveTimeStart +
                  "到" +
                  scope.row.effectiveTimeEnd
                : "用户领取" + scope.row.effectiveDayNum + "天内有效") +
              "内有效"
            }}
          </template>
        </af-table-column>
        <!-- <af-table-column label="核销机构" align="left">
          <template slot-scope="scope">
            {{
              scope.row.couponType == 1 || scope.row.couponType == 2
              ? "------------"
              : ""
            }}
            {{ scope.row.couponType == 3 ? ((!scope.row.verificationList || scope.row.verificationList.length == 0) ?
              "仅自家站点" : (scope.row.verificationNameList || []).toString()) : '' }}
          </template>
        </af-table-column> -->
        <!-- <af-table-column
          label="核销机构"
          prop="stationName"
        /> -->

        <af-table-column
          label="操作"
          fixed="right"
          align="left"
          class-name="small-padding fixed-width"
          width="250"
        >
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleView(scope.row)"
              >查看</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.row)"
              :disabled="scope.row.status !== '0'"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.status !== '3'"
              size="mini"
              type="text"
              @click="handleStatuUpdate(scope.row)"
            >
              {{ getStatusText(scope.row.status) }}
            </el-button>
            <el-button size="mini" type="text" @click="handleCopy(scope.row)"
              >复制模版</el-button
            >
          </template>
        </af-table-column>
      </el-table>
      <!-- <pagination :hidden="total > 0 ? false : true" :total="total" :page.sync="queryForm.pageNum"
        :limit.sync="queryForm.pageSize" :autoScroll="true" /> -->
      <el-pagination
        class="fr"
        style="margin-top: 8px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryForm.pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="queryForm.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    <div v-else style="text-align: center">
      亲，您的油站暂未启动优惠券功能，呦~
    </div>

    <!-- 添加或修改油站设备管理对话框 -->

    <el-drawer
      :title="title"
      :visible.sync="open"
      size="40%"
      direction="rtl"
      custom-class="add-drawer"
    >
      <p class="title-text" style="margin-left: 14px">优惠券-基础信息</p>
      <el-form
        ref="createForm"
        :model="createForm"
        :rules="rules"
        label-position="right"
        label-width="100px"
        class="formSty"
      >
        <el-form-item
          :rules="{
            required: true,
            message: '名称不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">优惠卷名称</span>
          <input type="text" class="form-control" style="width: 100%" />
        </el-form-item>
        <el-form-item>
          <span slot="label" class="slot_form_label">优惠卷ID</span>
          <input
            type="text"
            placeholder="无需输入，系统自动生成"
            disabled
            class="form-control"
            style="width: 100%"
          />
        </el-form-item>
        <!-- <el-form-item label="优惠劵标识(给油站备注)" prop="couponRemark" :rules="{
          required: true,
          message: '标签不能为空，不需要请删除此项',
          trigger: 'blur',
        }">
          <input type="text" class="form-control" v-model="createForm.couponRemark" style="width: 100%" />
        </el-form-item> -->
        <el-form-item
          label="优惠券类型"
          prop="couponType"
          :rules="{
            required: true,
            message: '请选择优惠券类型',
            trigger: 'change',
          }"
        >
          <span slot="label" class="slot_form_label">优惠券类型</span>
          <el-select
            v-model="createForm.couponType"
            clearable
            placeholder="请选择"
          >
            <el-option label="现金券" value="1" />
            <el-option label="折扣劵" value="2" />
            <!-- <el-option label="兑换劵" value="3" /> -->
          </el-select>
          <!-- <el-radio-group v-model="createForm.couponType">
            <el-radio label="1">现金券</el-radio>
            <el-radio label="2">折扣劵</el-radio>
            <el-radio label="3">兑换劵</el-radio>
          </el-radio-group> -->
        </el-form-item>

        <el-form-item
          v-show="createForm.couponType == 1"
          :rules="{
            required: true,
            message: '面值不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">优惠卷面值</span>
          <span class="lr-text">固定面值</span>
          <input type="text" class="form-control input-lr-text" />
          <span class="lr-text">元</span>
        </el-form-item>

        <el-form-item
          v-show="createForm.couponType == 2"
          :rules="{
            required: true,
            message: '折扣率不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">折扣率</span>
          <input type="text" class="form-control input-lr-text" />
          <span class="lr-text">%</span>
        </el-form-item>

        <el-form-item
          v-show="['1', '2'].includes(createForm.couponType)"
          :rules="{
            required: true,
            message: '使用条件不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">使用条件</span>
          <span class="lr-text" style="margin-left: 15px">消费满</span>
          <input type="text" style="" class="form-control input-lr-text" />
          <span class="lr-text">元</span>
        </el-form-item>

        <el-form-item
          prop="couponNum"
          :rules="{
            required: true,
            message: '生成数不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">生成数</span>
          <el-input
            v-model.number="createForm.couponNum"
            type="text"
            placeholder="请输入优惠券生成的数量"
            style="width: 40%; margin-right: 8px"
          ></el-input>
          <span class="lr-text">张</span>
        </el-form-item>

        <el-form-item
          :rules="{
            required: true,
            message: '使用条件不能为空',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">领取限制</span>
          <span class="lr-text">每人可领</span>
          <el-input
            type="text"
            placeholder="输入0表示无限制"
            style="width: 40%; margin: 0 8px"
          ></el-input>
          <span class="lr-text">张</span>
        </el-form-item>

        <el-form-item
          label="能否叠加"
          :rules="{
            required: true,
            message: '请选择能否叠加',
            trigger: 'change',
          }"
        >
          <!-- <span slot="label" class="slot_form_label">能否叠加</span> -->
          <el-radio-group>
            <el-radio label="1">是</el-radio>
            <el-radio label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          :rules="{
            required: true,
            message: '请选择发放时间',
            trigger: 'change',
          }"
        >
          <span slot="label" class="slot_form_label">发放时间</span>
          <el-date-picker
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </el-form-item>

        <!--
        <el-form-item label="优惠劵名称(给用户展示)" prop="couponName" v-if="createForm.couponType == 3" :rules="{
          required: createForm.couponType == 3,
          message: '请填写优惠券名称',
          trigger: 'blur',
        }">
          <input type="text" class="form-control" v-model="createForm.couponName" style="width: 180px" />
        </el-form-item> -->
        <el-form-item prop="effectiveTimeType">
          <span slot="label" class="slot_form_label">使用有效期</span>
          <div>
            <div>
              <el-radio-group v-model="createForm.effectiveTimeType">
                <el-radio label="1">固定时间段</el-radio>
                <el-radio label="2">固定天数</el-radio>
              </el-radio-group>
            </div>
            <div style="margin-top: 10px">
              <div v-if="createForm.effectiveTimeType == 1">
                <el-date-picker
                  style="width: 350px"
                  v-model="createForm.effectiveTime"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                >
                </el-date-picker>
              </div>
              <div v-if="createForm.effectiveTimeType == 2">
                自用户领取后
                <input
                  type="text"
                  class="form-control d-inline"
                  v-model.number="createForm.effectiveDayNum"
                  style="width: 80px"
                />
                天内有效
              </div>
            </div>
          </div>
        </el-form-item>

        <el-form-item
          prop="couponDetails"
          :rules="{
            required: true,
            message: '请填写优惠说明',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">优惠说明</span>
          <el-input
            type="text"
            placeholder="请输入优惠券优惠内容"
            v-model="createForm.couponDetails"
          ></el-input>
        </el-form-item>

        <el-form-item
          prop="couponDetails"
          :rules="{
            required: true,
            message: '请填写使用说明',
            trigger: 'blur',
          }"
        >
          <span slot="label" class="slot_form_label">使用说明</span>
          <el-input
            type="text"
            placeholder="请输入优惠券使用规则"
            v-model="createForm.couponDetails"
          ></el-input>
        </el-form-item>

        <p class="title-text">优惠券-关联站点</p>
        <el-form-item
          label="油企名"
          prop="couponType"
          :rules="{
            required: true,
            message: '请选择油企',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="createForm.enterpriseId"
            :clearable="true"
            filterable
            placeholder="请选择油企"
            style="width: 250px"
            @change="handleSelectChangeAddOrEdit"
          >
            <el-option
              v-for="(item, index) in enterpriseList"
              :key="index"
              :value="item.enterpriseId"
              :label="item.enterpriseName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item
          label="油站名"
          prop="couponType"
          :rules="{
            required: true,
            message: '请选择油站',
            trigger: 'change',
          }"
        >
          <el-select
            v-model="createForm.stationId"
            :clearable="true"
            filterable
            placeholder="请选择油站"
            style="width: 250px"
          >
            <el-option
              v-for="item in stationListForm"
              :key="item.stationId"
              :label="item.stationName"
              :value="item.stationId"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <p class="title-text">优惠券-关联商品</p>
        <el-form-item label="商品类型">
          <div>
            <div v-if="createForm.couponType != 3">
              <el-button type="primary">添加油品</el-button>
              <el-row style="margin-top: 14px">
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right"
                      ><i class="el-icon-error" style="color: red"></i
                    ></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right"
                      ><i class="el-icon-error" style="color: red"></i
                    ></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right"
                      ><i class="el-icon-error" style="color: red"></i
                    ></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right"
                      ><i class="el-icon-error" style="color: red"></i
                    ></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right"
                      ><i class="el-icon-error" style="color: red"></i
                    ></span>
                  </div>
                </el-col>
              </el-row>
            </div>

            <!-- <div>
              <el-button type="primary" style="margin-top: 16px;">添加非油品</el-button>
              <el-row style="margin-top: 14px;">
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right;"><i class="el-icon-error" style="color: red"></i></span>
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="commodity-item">
                    <span>92#</span>
                    <span style="float: right;"><i class="el-icon-error" style="color: red"></i></span>
                  </div>
                </el-col>
              </el-row>
            </div> -->
          </div>
        </el-form-item>

        <!-- <el-form-item label="优惠金额" prop="couponAmt" v-if="createForm.couponType == 1 || createForm.couponType == 2"
          :rules="{
            required: createForm.couponType == 1 || createForm.couponType == 2,
            message: '请填写优惠券适用条件',
            trigger: 'blur',
          }">
          <div v-if="createForm.couponType == 1">
            固定面值—<input type="text" class="form-control d-inline" v-model.number="createForm.couponAmt"
              style="width: 100px" />
            元
          </div>
          <div v-if="createForm.couponType == 2">
            折扣比例—<input type="text" class="form-control d-inline" v-model.number="createForm.couponAmt"
              style="width: 100px" />
            %
          </div>
        </el-form-item> -->
        <div v-if="createForm.couponType == 3">
          <p class="title-text">优惠券-核销方</p>
          <p style="text-align: center">（自己的站点是默认必选的核销商）</p>
          <div>
            <el-col :span="11">
              <el-table
                :data="unselectedCouponList"
                border
                size="mini"
                :resizable="false"
                highlight-current-row
                height="500"
                @selection-change="handleLeftChange"
                disabled
                ref="leftTable"
              >
                >
                <el-table-column label="可选">
                  <el-table-column
                    prop="phone"
                    label="机构"
                    type="selection"
                  ></el-table-column>
                  <el-table-column
                    prop="stationName"
                    label="机构"
                  ></el-table-column>
                  <el-table-column label="添加" width="60px" align="left">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        icon="el-icon-circle-plus-outline"
                        class="underline btn24"
                        size="mini"
                        @click="handleMoveLabel('right', scope.row)"
                        >添加</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="2" style="text-align: center">
              <el-button
                type="primary"
                size="mini"
                @click="toggleLabel"
                style="
                  margin-top: 200px;
                  text-align: center;
                  width: 30px;
                  padding-right: 0;
                  padding-left: 0;
                "
                :disabled="toggleable"
                >切换</el-button
              >
            </el-col>
            <el-col :span="11" style="margin-bottom: 20px">
              <el-table
                :data="selectedCouponList"
                border
                size="mini"
                highlight-current-row
                :resizable="false"
                height="500"
                @selection-change="handleRightChange"
                :loading="true"
                ref="rightTable"
              >
                <el-table-column label="已选" :resizable="false">
                  <el-table-column
                    prop="phone"
                    type="selection"
                  ></el-table-column>
                  <el-table-column
                    prop="stationName"
                    label="姓名"
                  ></el-table-column>
                  <el-table-column label="移除" width="60px" align="left">
                    <template slot-scope="scope">
                      <el-button
                        type="text"
                        icon="el-icon-remove-outline"
                        class="underline btn24"
                        size="mini"
                        @click="handleMoveLabel('left', scope.row)"
                        >移除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table-column>
              </el-table>
            </el-col>
          </div>
        </div>
      </el-form>
      <div style="text-align: right; padding: 14px">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-drawer>
    <CouponCreateCouponForm ref="CouponCreateCouponForm" :parm="params" />
       <!-- 自助优惠券核销 -->
    <CouponHeXiaoSelf
      :hexiaoSelfDialog.sync="hexiaoSelfDialog"
      :text="hexiaoSelfText"
    >
    </CouponHeXiaoSelf>
  </div>
</template>

<script>
import { listPrice } from "@/api/station/price";
import SelectDay from "@/components/SelectDay";
import { enterpriseList } from "@/api/station/orderHistory";
import { listEnterpriseStation } from "@/api/dept";
import CouponHeXiaoSelf from "./Coupon_HeXiao_self";
import Qr from "@/components/QrCode/coupon-qr.vue";
import {
  addInfo,
  verificationList,
  listInfo,
  updateInfo,
  changeCouponStatus,
  selectCouponEnableFalge,
} from "@/api/coupon";
import {
  creationList,
  creationDelete,
  createCoupon,
  getCouponDetails,
  getCouponCopyTemplate,
  modifyCoupon,
  updateCouponStatus,
} from "@/api/coupon/creation";
import CouponCreateCouponForm from "./Coupon_CreateCoupon_form.vue";

export default {
  name: "Coupon_CreateCoupon",
  data() {
    let validateOilNameList = (rule, value, callback) => {
      if (value.length == 0) {
        callback(new Error("请选择优惠券的使用油品"));
        return;
      }
      callback();
    };
    let validateEffectiveTimeType = (rule, value, callback) => {
      if (!value) {
        callback(new Error("请填入有效时间"));
        return;
      }
      if (value == 1) {
        if (this.createForm.effectiveTime.length == 0) {
          callback(new Error("请选择有效时间"));
          return;
        }
      }
      if (value == 2) {
        if (!this.createForm.effectiveDayNum) {
          callback(new Error("请填入有效天数"));
          return;
        }
      }
      callback();
    };
    return {
      //创建优惠券的时间
      isInput: false,
      dateRangeCreatedDate: [],
      couponEnabledFlag: "1",
      // 油站设备管理表格数据
      createForm: {
        couponRemark: "",
        couponName: "",
        couponDetails: "",
        couponType: "",
        couponAmt: "",
        oilIdLists: [],
        effectiveTimeType: "", //有效时间类型： 1，固定时间；2，领取后x天内有效
        effectiveTime: [],
        effectiveDayNum: 30,
        couponNum: 100,
        status: "1",
        stationId: null,
      },
      couponList: [],
      allVerificationList: [],
      day: [],
      cycle: [],

      deviceTypeOptions: [],
      stationOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 总条数
      total: 100,
      leftQuery: {},
      rightQuery: {},
      leftData: [],
      rightData: [],
      moveRightData: [],
      moveLeftData: [],
      // 查询参数
      queryForm: {
        pageNum: 1,
        pageSize: 10, // 初始值只能比10大
        couponName: null,
        couponRemark: null,
        couponType: null,
        levelId: this.levelId,
        couponRemark: null,
        status: null,
        getCreateTime: null,
        stationId: null,
      },
      hexiaoSelfDialog:false,
      hexiaoSelfText:'',
      // 表单校验
      rules: {
        oilIdLists: [
          { required: true, message: "请选择适用油品", trigger: "change" },
          { validator: validateOilNameList, trigger: "change" },
        ],
        effectiveTimeType: [
          { required: true, message: "请输入有效期类型", trigger: "change" },
          { validator: validateEffectiveTimeType, trigger: "change" },
        ],
      },
      timeSelect: [
        ,
        ["周天", "周一", "周二", "周三", "周四", "周五", "周六"],
        [
          "1号",
          "2号",
          "3号",
          "4号",
          "5号",
          "6号",
          "7号",
          "8号",
          "9号",
          "10号",
          "11号",
          "12号",
          "13号",
          "14号",
          "15号",
          "16号",
          "17号",
          "18号",
          "19号",
          "20号",
          "21号",
          "22号",
          "23号",
          "24号",
          "25号",
          "26号",
          "27号",
          "28号",
          "29号",
          "30号",
          "31号",
        ],
      ],
      currentOilList: [],
      enterpriseList: [],
      stationList: [],
      stationListForm: [],
      collapse: false,
      selectionChangeList: [],
      params: {},
    };
  },
  created() {
    if (this.$route.query.marking) {
      this.handleAdd();
    }
    this.init();
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId, "search");
    }
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
    toggleable() {
      if (this.moveRightData.length === 0 && this.moveLeftData.length === 0) {
        return true;
      }
      return false;
    },
    selectedCouponList() {
      return this.allVerificationList.filter((ele) => {
        if (this.createForm.verificationList == null) {
          this.createForm.verificationList = [];
        }
        return this.createForm.verificationList.includes(ele.stationId);
      });
    },
    unselectedCouponList() {
      return this.allVerificationList.filter((ele) => {
        if (this.createForm.verificationList == null) {
          this.createForm.verificationList = [];
        }
        return !!!this.createForm.verificationList.includes(ele.stationId);
      });
    },
  },
  components: {
    SelectDay: SelectDay,
    CouponCreateCouponForm,
    CouponHeXiaoSelf,
    Qr: Qr,
  },
  methods: {
    // 优惠券自助核销
    showSelfHexiao() {
      this.hexiaoSelfDialog = true;
    },
    // 查询油企
    getStatusText(status) {
      if (status === "0") {
        return "启动";
      } else if (status === "1") {
        return "停止";
      } else if (status === "2") {
        return "启动";
      } else {
        return "";
      }
    },

    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    // 查询油站
    getStationList(val, key) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        if (key === "search") {
          this.stationList = res;
        } else {
          this.stationListForm = res;
        }
      });
    },
    // 搜索选择油企
    handleSelectChange(val) {
      this.stationList = [];
      this.queryForm.stationId = null;
      this.getStationList(val, "search");
    },
    handleSelectChangeAddOrEdit(val) {
      this.stationListForm = [];
      this.createForm.stationId = null;
      this.getStationList(val);
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.couponName + '"该优惠券吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateInfo({
            id: row.id,
            status: row.status,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },

    /** 查询优惠券模板信息*/
    getList() {
      creationList(this.addDateRange(this.queryForm, this.dateRangeCreatedDate))
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.total = 0;
              this.couponList = [];
            } else {
              this.total = res.total;
              this.couponList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取优惠券列表失败~");
        });
    },
    handleSizeChange(size) {
      this.queryForm.pageSize = size;
      this.getList();
    },
    handleCurrentChange(page) {
      this.queryForm.pageNum = page;
      this.getList();
    },

    getTodayDateString() {
      const date = new Date();
      let y = date.getFullYear();
      let m = date.getMonth().toString();
      let s = date.getDate().toString();
      m = "" + (m.length == 1 ? "0" : "") + m;
      s = "" + (s.length == 1 ? "0" : "") + s;
      return "" + y + ":" + m + ":" + s;
    },
    handleMoveLabel(direction, row) {
      if (!this.createForm.verificationList) {
        this.createForm.verificationList = [];
      }
      console.log("22");
      if (direction == "right") {
        this.createForm.verificationList.push(row.stationId);
      } else {
        this.createForm.verificationList =
          this.createForm.verificationList.filter((ele) => {
            return ele != row.stationId;
          });
      }
      this.createForm = { ...this.createForm };
    },
    handleFlagChange() {
      const that = this;
      let text = this.couponEnabledFlag === "1" ? "启用" : "停用";
      this.$confirm('确认要"' + text + '"优惠券功能吗?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return changeCouponStatus(that.couponEnabledFlag);
        })
        .then(() => {
          that.msgSuccess(text + "成功");
        })
        .catch(function () {
          that.couponEnabledFlag = that.couponEnabledFlag === "0" ? "1" : "0";
        });
    },
    handleStatusChange(row) {
      let text = row.status === "1" ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.couponName + '"该优惠券吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return updateInfo({
            id: row.id,
            status: row.status,
          });
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
    },
    getVerificationList() {
      verificationList({
        pageNum: 1,
        pageSize: 1000,
      })
        .then((res) => {
          if (res.code == 200) {
            if (res.rows == null) {
              this.allVerificationList = [];
            } else {
              this.allVerificationList = res.rows;
            }
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("亲，拉取核销机构失败~");
        });
    },
    toggleLabel() {
      if (this.moveLeftData.length !== 0) {
        this.createForm.verificationList =
          this.createForm.verificationList.filter((ele) => {
            return ele != this.moveLeftData;
          });
        this.createForm = { ...this.createForm };
        return;
      }
      if (this.moveRightData.length !== 0) {
        this.createForm.verificationList = [
          ...new Set(
            this.createForm.verificationList.concat(this.moveRightData)
          ),
        ].filter((ele) => {
          return !!ele;
        });
        this.createForm = { ...this.createForm };
        return;
      }
      return;
    },
    handleLeftChange(val) {
      let changeArr = [];
      val.map((ele) => {
        changeArr.push(ele.stationId);
      });
      this.moveLeftData = [];
      this.moveRightData = changeArr;
      this.$refs.rightTable.clearSelection();
    },
    handleRightChange(val) {
      let changeArr = [];
      val.map((ele) => {
        changeArr.push(ele.stationId);
      });
      this.moveLeftData = changeArr;
      this.moveRightData = [];
      this.$refs.leftTable.clearSelection();
    },
    init() {
      selectCouponEnableFalge()
        .then((res) => {
          if (res.code == 200) {
            this.couponEnabledFlag = res.data.toString();
            this.getList();
            this.getVerificationList();
          } else {
            throw new Error("");
          }
        })
        .catch((err) => {
          this.msgError("拉取优惠券配置失败");
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.createForm.pageNum = 1;
      this.getList();
    },
    deviceNoInput(value) {
      this.createForm.posQueue = value;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryForm.pageNum = 1;
      this.queryForm.pageSize = 10;
      this.dateRangeCreatedDate = [];
      //this.queryForm.couponRemark=null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.params = {
        drawerShow: true,
        drawerType: "new",
        createForm: {
          isMergeUse: 0,
          couponRemark: "",
          couponName: "",
          couponDetails: "",
          couponType: "",
          couponAmt: "",
          oilIdLists: [],
          effectiveTimeType: "", //有效时间类型： 1，固定时间；2，领取后x天内有效
          effectiveTime: [],
          effectiveDayNum: 30,
          couponNum: 100,
          status: "1",
          enterpriseId: this.$store.state.user.enterpriseId,
          stationId:
            this.$store.state.user.userLevel === "2"
              ? this.$store.state.user.stationId
              : "",
        },
      };
      this.$nextTick(() => {
        if (this.$store.state.user.userLevel === "1") {
          this.$refs.CouponCreateCouponForm.getStationList(
            this.$store.state.user.presentEnterprise.enterpriseId
          );
        }
        this.$refs.CouponCreateCouponForm.clearValidate();
      });
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      try {
        // 调用 getCouponDetails 方法，并传入行数据的 id 属性
        const response = await getCouponDetails(row.id);

        // 检查是否成功获取优惠券详情数据
        if (response && response.data) {
          // 将获取的数据填充到 createForm 对象中
          this.params = {
            drawerShow: true,
            drawerType: "edit",
            createForm: Object.assign({}, response.data),
          };

          this.$nextTick(() => {
            if (this.$store.state.user.userLevel === "1") {
              this.$refs.CouponCreateCouponForm.getStationList(
                this.$store.state.user.presentEnterprise.enterpriseId
              );
              this.isInput = true;
            }
            this.$refs.CouponCreateCouponForm.clearValidate();
          });
        } else {
          console.error("获取优惠券详情失败");
        }
      } catch (error) {
        console.error("获取优惠券详情发生错误", error);
      }
    },
    async handleCopy(row) {
      try {
        // 调用 getCouponDetails 方法，并传入行数据的 id 属性
        const response = await getCouponCopyTemplate(row.id);

        // 检查是否成功获取优惠券详情数据
        if (response && response.data) {
          // 将获取的数据填充到 createForm 对象中
          this.params = {
            drawerShow: true,
            drawerType: "new",
            createForm: Object.assign({}, response.data),
          };

          this.$nextTick(() => {
            if (this.$store.state.user.userLevel === "1") {
              this.$refs.CouponCreateCouponForm.getStationList(
                this.$store.state.user.presentEnterprise.enterpriseId
              );
              this.isInput = true;
            }
            this.$refs.CouponCreateCouponForm.clearValidate();
          });
        } else {
          console.error("获取优惠券详情失败");
        }
      } catch (error) {
        console.error("获取优惠券详情发生错误", error);
      }
    },
    // 异步处理优惠券状态更新方法
    async handleStatuUpdate(row) {
      try {
        let newStatus;

        // 根据当前状态确定新的状态值
        if (row.status === "0") {
          newStatus = "1"; // 如果当前状态为 '0'，则将新状态设置为 '1'（停用变为启用）
        } else if (row.status === "1") {
          newStatus = "2"; // 如果当前状态为 '1'，则将新状态设置为 '2'（启用变为停用）
        } else if (row.status === "2") {
          newStatus = "1"; // 如果当前状态为 '2'，则将新状态设置为 '1'（停用变为启用）
        } else {
          console.error("无效的状态值:", row.status);
          return;
        }

        // 调用 API 更新优惠券状态
        await updateCouponStatus(row.id, newStatus);

        // 更新表格行中的状态值
        row.status = newStatus;

        // 提示用户操作成功
        this.$message.success("优惠券状态更新成功。");
      } catch (error) {
        console.error("优惠券状态更新失败:", error);
        this.$message.error("优惠券状态更新失败，请重试。");
      }
    },

    async handleView(row) {
      try {
        // 清除之前的表单校验状态

        // 调用 getCouponDetails 方法，并传入行数据的 id 属性
        const response = await getCouponDetails(row.id);

        // 检查是否成功获取优惠券详情数据
        if (response && response.data) {
          // 将获取的数据填充到 createForm 对象中
          const createForm = Object.assign({}, response.data);
          this.params = {
            drawerShow: true,
            drawerType: "read",
            createForm,
          };

          this.$nextTick(() => {
            if (this.$store.state.user.userLevel === "1") {
              this.$refs.CouponCreateCouponForm.getStationList(
                this.$store.state.user.presentEnterprise.enterpriseId
              );
              this.isInput = true;
              this.$refs.CouponCreateCouponForm.clearValidate();
            }
          });
        } else {
          console.error("获取优惠券详情失败");
        }
      } catch (error) {
        console.error("获取优惠券详情发生错误", error);
      }
    },
    // 获取n天后的日期
    getTargetDate(startDate, days) {
      var startTime = new Date(startDate).getTime();
      var diff = days * 86400 * 1000;
      var endTime = startTime + diff;
      var d = new Date(endTime);
      var CurrentDate = "";
      CurrentDate += d.getFullYear();
      //var year=(d.getFullYear())+"-"+(d.getMonth()+1)+"-"+(d.getDate());
      if (d.getMonth() + 1 > 9) {
        CurrentDate += "-" + (d.getMonth() + 1);
      } else {
        CurrentDate += "-0" + (d.getMonth() + 1);
      }
      if (d.getDate() > 9) {
        CurrentDate += "-" + d.getDate();
      } else {
        CurrentDate += "-0" + d.getDate();
      }
      return CurrentDate;
    },
    getCurrentDate() {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var day = date.getDate();
      month = month > 9 ? month : "0" + month;
      day = day < 10 ? "0" + day : day;
      return year + "-" + month + "-" + day;
    },
    formatterStatus(row, column) {
      const types = {
        0: "待生效",
        1: "生效中",
        2: "生效已暂停",
        3: "已失效",
      };
      return types[row.status] ?? "";
    },
    formatterCouponType(row, column) {
      const types = {
        1: "现金劵",
        2: "折扣劵",
        3: "兑换券",
        4: "洗车券",
        5: "立减券"
      };
      return types[row.couponType] ?? "";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["createForm"].validate((valid) => {
        if (valid) {
        }
      });
    },
    selectionChange(selection) {
      this.selectionChangeList = selection;
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm(`确认删除勾选的优惠卷吗？`).then(() => {
        let ids = this.selectionChangeList.map((item) => item.id);
        creationDelete(ids).then((res) => {
          if (res && res.code === 200) {
            this.$message.success(res.msg);
            this.selectionList = [];
            this.getList();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
  },
  // watch: {
  //   "this.drawer.show": {
  //     handler(newValue) {
  //       console.log(12345889);
  //       if (newValue === true) {
  //         this.selectionList = []; // 清空 selectionList 数组
  //         this.getList(); // 调用 getList 方法
  //       }
  //     },
  //     immediate: false, // 默认值为 true，设置为 false 以避免初始加载时立即触发
  //   },
  // },
};
</script>
<style lang="scss" scoped>
::v-deep .add-drawer {
  overflow-y: auto;
}

.formSty {
  padding: 20px;
}

.title-text {
  // padding: 0 16px;
  font-size: 24px;
}

.input-lr-text {
  display: inline-block;
  width: 32%;
  margin: 0 8px;
}

.lr-text {
  display: inline-block;
  vertical-align: top;
}

.commodity-item {
  border: 1px solid #9a9a9a;
  border-radius: 20px;
  padding: 0 8px;
  margin: 0 8px 8px 0;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 70px;
}

// .slot_form_label {
//   position: relative;
// }
// .slot_form_label::after {
//   content: '*';
//   width: 100%;
//   display: inline-block;
//   position: absolute;
//   left: -13px;
//   color: red;
// }
// ::v-deep .el-form-item__label {
//   text-align: justify;
//   max-height: 40px;
// }

// ::v-deep .el-form-item__label::after {
//   content: ' ';
//   width: 100%;
//   display: inline-block;
// }
// ::v-deep .el-form-item__label::before {
//   display: none;
// }
::v-deep .el-drawer__body {
  padding: 16px;
}

::v-deep .el-radio-group {
  vertical-align: baseline;
}
</style>
